#!/bin/bash

set -e
cpdata() {
    if [ "x$MSYSTEM" = "xMSYS" ]; then
        mkdir -p shadowgate-windows-i686
        [ -f ../shadowgate ] && cp -f ../shadowgate shadowgate-windows-i686/
        cp -f ../*.bat ../*.dll  ../*.mmdb ../*.conf shadowgate-windows-i686/
        git add shadowgate-windows-i686
    else
        mkdir -p shadowgate-linux-x86_64
        cp -f ../install.sh ../shadowgate shadowgate-linux-x86_64/
        git add  shadowgate-linux-x86_64
    fi
}

release_dir="shadowgate-release2"
[ -n "$gituser" ] || read -p "gituser: " gituser
[ -n "$gitpass" ] || read -s -p "gitpass: " gitpass

gitdo() {
    /usr/bin/expect <<EOF
spawn $*
set timeout -1
expect {
"Username" { send "$gituser\r"; exp_continue; }
"Password" { send "$gitpass\r"; exp_continue; }
eof        { }
}
EOF
}

docommit() {
    echo -e "MODIFIED FILE DETECTED, PRESS ANY KEY TO DO UPDATING..."
    read a
    git config user.email "windowhero@sina.com"
    git config user.name "windowhero"
    git commit -am "UPDATE `date +%FT%T%z`"
    gitdo git push -f
}

[ ! -f Makefile ] || make
[ -d $release_dir ] || gitdo git clone https://gitee.com/windowhero/$release_dir
[ -d $release_dir ] || { echo "FAIL TO CLONE $release_dir"; exit 1; }
echo cd $release_dir
cd $release_dir
git config pull.rebase false
git reset --hard `git log --reverse | head -n 1 | awk '{print $2}'` >/dev/null
rm -rf *
git checkout . >/dev/null 2>&1
gitdo git pull
cpdata
git status
if false; then :;
elif git status | grep 'modified'                  >/dev/null; then docommit;
elif git status | grep 'Changes to be committed'   >/dev/null; then docommit;
fi
git log | head
